<!-- QuestionDetails.vue -->
<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import ChatComment from '@/components/ChatComment.vue' 
import ChatComponent from '@/components/ChatComponent.vue' 
import CEditor from '@/components/CEditor.vue'
import * as CommentData from '@/stores/mockdata'
import { ElMessage } from 'element-plus'

// 响应式数据
const router = useRouter()
const commentData = ref([])
const isDetail = ref(true)
const selectedLanguage = ref('c')
const codeValue = ref('')
const runResult = ref('')
const codeEditor = ref(null)

// 快捷键帮助对话框
const showShortcutHelp = ref(false)

// 自定义代码模板
const customTemplate = `#include <stdio.h>

int main() {
    // 请在这里编写超级玛丽的字符画输出代码
    printf("****************\\\\n");
    printf("####....#.\\\\n");
    printf("#..###.....##....\\\\n");
    printf("###.......######\\\\n");
    printf("###...............\\\\n");
    printf("###...............\\\\n");
    printf("####............\\\\n");
    printf("#####............\\\\n");
    printf("####............\\\\n");
    printf("###...............\\\\n");
    printf("##................\\\\n");
    printf("#.................\\\\n");
    return 0;
}`

// 先定义所有函数
// 运行代码
const runCode = () => {
  if (!codeValue.value.trim()) {
    runResult.value = '错误：请先输入代码'
    ElMessage.warning('请先输入代码')
    return
  }
  
  runResult.value = '正在编译运行...\n\n'
  
  setTimeout(() => {
    runResult.value += '编译成功！\n'
    runResult.value += '开始执行程序...\n\n'
    
    setTimeout(() => {
      runResult.value += '****************\n'
      runResult.value += '####....#.\n'
      runResult.value += '#..###.....##....\n'
      runResult.value += '###.......######\n'
      runResult.value += '###...............\n'
      runResult.value += '###...............\n'
      runResult.value += '####............\n'
      runResult.value += '#####............\n'
      runResult.value += '####............\n'
      runResult.value += '###...............\n'
      runResult.value += '##................\n'
      runResult.value += '#.................\n\n'
      runResult.value += '程序执行完毕，退出代码: 0'
    }, 1000)
  }, 1500)
}

// 重置代码
const resetCode = () => {
  if (codeEditor.value) {
    codeEditor.value.setCode(customTemplate)
    runResult.value = '代码已重置为题目模板'
  }
}

// 格式化代码
const formatCode = () => {
  if (codeEditor.value) {
    const currentCode = codeEditor.value.getCode()
    const formatted = currentCode
      .replace(/\t/g, '    ')
      .replace(/\n\s*\n/g, '\n\n')
      .trim() + '\n'
    
    codeEditor.value.setCode(formatted)
    runResult.value = '代码已格式化'
    ElMessage.success('代码已格式化')
  }
}

// 切换视图
const toggleView = () => {
  isDetail.value = !isDetail.value
  ElMessage.info(`已切换到${isDetail.value ? '题目描述' : '讨论区'}`)
}

// 显示帮助
const showHelp = () => {
  showShortcutHelp.value = true
}

// 提交代码
const submitCode = () => {
  router.push('/student/question/result')
}

// 现在定义快捷键配置（避免所有系统级冲突）
const shortcuts = {
  run: {
    keys: ['F9', 'Ctrl+Enter'],
    description: '运行代码',
    action: runCode
  },
  submit: {
    keys: ['Ctrl+Shift+S'],
    description: '提交代码',
    action: submitCode
  },
  reset: {
    keys: ['Ctrl+Shift+R'],
    description: '重置代码',
    action: resetCode
  },
  format: {
    keys: ['Ctrl+Shift+F'],
    description: '格式化代码',
    action: formatCode
  },
  toggleView: {
    keys: ['Ctrl+Q', 'Ctrl+`'],
    description: '切换题目/讨论区视图',
    action: toggleView
  },
  help: {
    keys: ['F2'],
    description: '显示快捷键帮助',
    action: showHelp
  }
}

// 处理键盘事件
const handleKeyDown = (event) => {
  const { ctrlKey, shiftKey, altKey, key } = event
  
  // 防止在输入框中触发快捷键
  if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
    return
  }

  // 构建按键组合标识
  let keyCombo = ''
  if (ctrlKey) keyCombo += 'Ctrl+'
  if (altKey) keyCombo += 'Alt+'
  if (shiftKey) keyCombo += 'Shift+'
  keyCombo += key

  // 检查匹配的快捷键
  for (const [name, shortcut] of Object.entries(shortcuts)) {
    if (shortcut.keys.includes(keyCombo)) {
      event.preventDefault()
      event.stopPropagation()
      shortcut.action()
      
      // 显示操作反馈（除了帮助快捷键本身）
      if (name !== 'help') {
        ElMessage.success(`执行: ${shortcut.description}`)
      }
      return
    }
  }

  // 单独处理 F9
  if (key === 'F9') {
    event.preventDefault()
    runCode()
    ElMessage.success('执行: 运行代码')
  }

  // 单独处理 F2
  if (key === 'F2') {
    event.preventDefault()
    showShortcutHelp.value = true
  }
}

// 处理评论更新
const handleUpdateComments = (updatedComments) => {
  console.log('评论更新:', updatedComments)
  commentData.value = updatedComments
}

const formattedComments = computed(() => {
  return commentData.value.map(comment => ({
    ...comment,
    isLike: comment.isLike || null,
    likeNum: comment.likeNum || 0,
    reply: comment.reply || []
  }))
})

// 语言选项
const languageOptions = [
  { value: 'c', label: 'C' },
  { value: 'java', label: 'Java' },
  { value: 'cpp', label: 'C++' },
  { value: 'python', label: 'Python' }
]

// 处理代码变化
const handleCodeChange = (newCode) => {
  codeValue.value = newCode
  console.log('代码已更新:', newCode)
}

// 处理编译状态
const handleCompileStatus = (status) => {
  console.log('编译状态:', status)
  
  if (status.hasErrors) {
    const errorCount = status.errors.filter(e => e.severity === 8).length
    const warningCount = status.errors.filter(e => e.severity === 4).length
    runResult.value = `编译发现 ${errorCount} 个错误，${warningCount} 个警告`
  } else {
    runResult.value = '代码语法检查通过，可以运行'
  }
}

// 处理编译请求
const handleCompileRequest = (code) => {
  console.log('编译请求:', code)
  runCode()
}

// 组件生命周期
onMounted(() => {
  commentData.value = CommentData.comment?.data || []
  console.log('加载的评论数据:', commentData.value)
  
  // 注册全局键盘事件监听器
  document.addEventListener('keydown', handleKeyDown)
})

onBeforeUnmount(() => {
  // 清理事件监听器
  document.removeEventListener('keydown', handleKeyDown)
})
</script>

<template>
  <div class="question-details">
    <el-row :gutter="20">
      <el-col :span="7">
        <div class="details-section">
          <!-- 切换标签 -->
          <div class="tab-switcher">
            <el-link 
              type="info" 
              :underline="false" 
              @click="isDetail = true" 
              :class="{ active: isDetail }"
            >
              题目描述
            </el-link>
            <el-link 
              type="info" 
              :underline="false" 
              @click="isDetail = false"
              :class="{ active: !isDetail }"
            >
              查看讨论区
            </el-link>
          </div>

          <!-- 题目详情 -->
          <div v-if="isDetail" class="question-content">
            <div class="section">
              <h3>题目背景</h3>
              <p>本题是洛谷的试机题目，可以帮助了解洛谷的使用。建议完成本题目后继续尝试 P1001、P1008。</p>
            </div>
            
            <div class="section">
              <h3>题目描述</h3>
              <p>超级玛丽是一个非常经典的游戏。请你用字符画的形式输出超级玛丽中的一个场景。</p>
            </div>
            
            <div class="section">
              <h3>输入格式</h3>
              <p>无</p>
            </div>
            
            <div class="section">
              <h3>输出格式</h3>
              <p>如描述。</p>
            </div>
            
            <div class="section">
              <h3>输入输出样例</h3>
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="code-sample">
                    <h4>输入</h4>
                    <pre>无</pre>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="code-sample">
                    <h4>输出</h4>
                    <pre>****************
                      ####....#.
                      #..###.....##....
                      ###.......######
                      ###...............
                      ###...............
                      ####............
                      #####............
                      ####............
                      ###...............
                      ##................
                      #.................</pre>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
          
          <!-- 讨论区 -->
          <div class="remark" v-else>
            <div v-if="formattedComments.length > 0">
              <chat-comment 
                :comments="formattedComments" 
                @update-comments="handleUpdateComments"
              />
            </div>
            <div v-else class="empty-comments">
              <el-empty description="暂无评论" />
            </div>
          </div>
        </div>
      </el-col>

      <el-col :span="10">
        <div class="code-section">
          <!-- 代码编辑器区域 -->
          <div class="section">
            <div class="editor-header">
              <h3>提交代码</h3>
              <div class="editor-actions">
                <el-button size="small" @click="resetCode">重置题目 (Ctrl+Shift+R)</el-button>
                <el-button size="small" @click="formatCode">格式化 (Ctrl+Shift+F)</el-button>
                <el-button size="small" type="text" @click="showShortcutHelp = true">
                  <el-icon><QuestionFilled /></el-icon>
                  快捷键 (F2)
                </el-button>
              </div>
            </div>
            <div class="editor-controls">
              <el-select v-model="selectedLanguage" placeholder="选择语言" style="width: 120px;">
                <el-option
                  v-for="item in languageOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-button size="small" type="success" @click="runCode">运行 (F9)</el-button>
              <el-button size="small" type="primary" @click="submitCode">提交 (Ctrl+Shift+S)</el-button>
            </div>
            
            <!-- 使用 CEditor 组件 -->
            <CEditor
              :code-template="customTemplate"
              :show-error-panel="true"
              @code-change="handleCodeChange"
              @compile-status="handleCompileStatus"
              @compile-request="handleCompileRequest"
              ref="codeEditor"
            />
          </div>

          <!-- 运行结果 -->
          <div class="section">
            <h3>运行结果</h3>
            <div class="result-output">
              <pre>{{ runResult || '运行结果将显示在这里...' }}</pre>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="7">
        <chat-component></chat-component>
      </el-col>
    </el-row>

    <!-- 快捷键帮助对话框 -->
    <el-dialog
      v-model="showShortcutHelp"
      title="快捷键帮助"
      width="500px"
      center
    >
      <div class="shortcut-help">
        <h3>可用快捷键</h3>
        <div class="shortcut-table">
          <div class="shortcut-row" v-for="(shortcut, name) in shortcuts" :key="name">
            <div class="shortcut-keys">
              <kbd v-for="key in shortcut.keys" :key="key" class="key">{{ key }}</kbd>
            </div>
            <div class="shortcut-description">{{ shortcut.description }}</div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="showShortcutHelp = false">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.question-details {
  padding: 20px;
  
  .tab-switcher {
    margin-bottom: 20px;
    
    .el-link {
      margin-right: 20px;
      font-size: 16px;
      padding: 8px 16px;
      border-radius: 6px;
      transition: all 0.3s ease;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      &.active {
        color: #409eff;
        background-color: #ecf5ff;
        font-weight: 500;
      }
    }
  }
  
  .section {
    margin-bottom: 24px;
    
    h3 {
      margin-bottom: 12px;
      color: #333;
      border-left: 4px solid #409eff;
      padding-left: 12px;
      font-size: 18px;
    }
    
    p {
      line-height: 1.6;
      color: #666;
      margin-bottom: 8px;
    }
  }

  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    h3 {
      margin-bottom: 0;
      border: none;
      padding-left: 0;
    }

    .editor-actions {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }
  
  .code-sample {
    background: #f5f5f5;
    padding: 12px;
    border-radius: 4px;
    border: 1px solid #e8e8e8;
    
    h4 {
      margin-bottom: 8px;
      color: #333;
      font-size: 14px;
      font-weight: 600;
    }
    
    pre {
      margin: 0;
      font-family: 'Courier New', monospace;
      font-size: 13px;
      line-height: 1.4;
      color: #333;
      white-space: pre-wrap;
    }
  }
  
  .empty-comments {
    padding: 40px 0;
    text-align: center;
  }
  
  .editor-controls {
    display: flex;
    gap: 10px;
    margin-bottom: 12px;
    align-items: center;
  }
  
  .result-output {
    background: #f5f5f5;
    padding: 16px;
    border-radius: 4px;
    min-height: 120px;
    border: 1px solid #e8e8e8;
    
    pre {
      margin: 0;
      white-space: pre-wrap;
      font-family: 'Courier New', monospace;
      font-size: 13px;
      line-height: 1.4;
      color: #333;
    }
  }
}

// 快捷键帮助对话框样式
.shortcut-help {
  h3 {
    margin-bottom: 16px;
    color: #333;
    text-align: center;
  }

  .shortcut-table {
    .shortcut-row {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .shortcut-keys {
        display: flex;
        gap: 6px;
        min-width: 160px;

        .key {
          background: #f1f3f4;
          border: 1px solid #dadce0;
          border-radius: 4px;
          padding: 4px 8px;
          font-size: 12px;
          font-family: 'Courier New', monospace;
          color: #3c4043;
          box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }
      }

      .shortcut-description {
        color: #5f6368;
        font-size: 14px;
      }
    }
  }
}

// 暗色模式支持
@media (prefers-color-scheme: dark) {
  .question-details {
    .section h3 {
      color: #e4e4e4;
    }
    
    .code-sample,
    .result-output {
      background: #2d2d2d;
      border-color: #444;
      
      h4, pre {
        color: #e4e4e4;
      }
    }
    
    .tab-switcher .el-link {
      &:hover {
        background-color: #2d2d2d;
      }
      
      &.active {
        background-color: #1e3a5f;
      }
    }
  }

  .shortcut-help {
    .shortcut-row .shortcut-keys .key {
      background: #3d3d3d;
      border-color: #555;
      color: #e4e4e4;
    }

    .shortcut-row .shortcut-description {
      color: #b0b0b0;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .question-details {
    padding: 16px;
    
    .editor-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
      
      .editor-actions {
        width: 100%;
        justify-content: flex-start;
      }
    }
    
    .editor-controls {
      flex-wrap: wrap;
    }
  }
}
</style>